<template>
  <div class="department-management-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="12">
        <el-button :icon="Plus" type="primary" @click="handleEdit($event)">
          添加
        </el-button>
        <el-button :icon="Delete" type="danger" @click="handleDelete($event)">
          批量删除
        </el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="12">
        <el-form inline :model="queryForm" @submit.prevent>
          <el-form-item>
            <el-input
              v-model.trim="queryForm.name"
              clearable
              placeholder="请输入名称"
            />
          </el-form-item>
          <el-form-item>
            <el-button :icon="Search" type="primary" @click="queryData">
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table
      v-loading="listLoading"
      border
      :data="list"
      default-expand-all
      row-key="id"
      :tree-props="{ children: 'children' }"
      @selection-change="setSelectRows"
    >
      <el-table-column show-overflow-tooltip type="selection" />
      <el-table-column label="名称" prop="name" show-overflow-tooltip />
      <el-table-column
        label="父节点Id"
        prop="parentId"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        label="排序"
        prop="sort"
        align="center"
        width="100"
        show-overflow-tooltip
      />
      <el-table-column
        label="创建时间"
        prop="createTime"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column label="操作" width="200" align="center">
        <template #default="{ row }">
          <el-button text type="primary" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button
            :disabled="!row.parentId"
            text
            type="primary"
            @click="handleDelete({ row })"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty class="vab-data-empty" description="暂无数据" />
      </template>
    </el-table>
    <edit ref="editRef" @fetch-data="refreshList" />
  </div>
</template>

<script>
  import {
    doDelete,
    fetchDeptList,
    getDetail,
    getDeptTreeList,
  } from '@/api/departmentManagement'
  import { Delete, Plus, Search } from '@element-plus/icons-vue'

  export default defineComponent({
    name: 'DepartmentManagement',
    components: {
      Edit: defineAsyncComponent(() =>
        import('./components/DepartmentManagementEdit')
      ),
    },
    setup() {
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')

      const state = reactive({
        editRef: null,
        list: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        selectRows: '',
        queryForm: {
          title: '',
        },
        DeptTreeList: [],
      })

      const setSelectRows = (val) => {
        state.selectRows = val
      }
      const handleEdit = async (row) => {
        if (row.id) {
          try {
            const { data: data } = await getDetail({ deptId: row.id })
            state.editRef.showEdit(data, state.DeptTreeList)
          } catch (e) {
            console.error(e)
          }
        } else {
          state.editRef.showEdit('', state.DeptTreeList)
        }
      }
      const handleDelete = async (row) => {
        if (row.id) {
          try {
            $baseConfirm('你确定要删除当前项吗', null, async () => {
              const { msg } = await doDelete({ ids: row.id })
              $baseMessage(msg, 'success', 'vab-hey-message-success')
              refreshList()
            })
          } catch (e) {
            console.error(e)
          }
        } else {
          if (state.selectRows.length > 0) {
            try {
              const ids = state.selectRows.map((item) => item.id).join()
              $baseConfirm('你确定要删除选中项吗', null, async () => {
                const { msg } = await doDelete({ ids })
                $baseMessage(msg, 'success', 'vab-hey-message-success')
                refreshList()
              })
            } catch (e) {
              console.error(e)
            }
          } else {
            $baseMessage('未选中任何行', 'error', 'vab-hey-message-error')
          }
        }
      }
      const queryData = () => {
        fetchData()
      }
      const refreshList = () => {
        fetchData()
        fetchDeptLists()
      }
      const fetchData = async () => {
        try {
          state.listLoading = true
          const { data: data } = await getDeptTreeList(state.queryForm)
          state.DeptTreeList = data
          state.listLoading = false
        } catch (e) {
          console.error(e)
        }
      }
      const fetchDeptLists = async () => {
        try {
          state.listLoading = true
          const { data: data } = await fetchDeptList(state.queryForm)
          state.list = data
          state.listLoading = false
        } catch (e) {
          console.error(e)
        }
      }
      onMounted(() => {
        fetchData()
        fetchDeptLists()
      })

      return {
        ...toRefs(state),
        setSelectRows,
        handleEdit,
        handleDelete,
        queryData,
        fetchData,
        refreshList,
        Delete,
        Plus,
        Search,
      }
    },
  })
</script>
